/*
 * Memory.java
 * 
 * Team Dovahkiin:
 * Major Bruno, Matthew Selfors
 * 
 * This class is a simulation of the memory used in the SC-2.
 */

package phaseI;

/**
 * This class is a simulation of the memory used in the SC-2.
 * 
 * @author Major Bruno
 * @author Matthew Selfors
 * @version 1.0
 */
public class Memory {

	/**
	 * The length of a byte.
	 */
	private static final int BYTE_LENGTH = 8;
	
	/**
	 * The length of a word.
	 */
	private static final int WORD_LENGTH = 16;
	
	/**
	 * The number of memory locations.
	 */
	private static final int MEM_SIZE = 65536;

	/**
	 * An array representing memory locations.
	 */
	public String[] memory;

	/**
	 * Calls super() and initializes the memory locations with random values.
	 */
	public Memory(final String[] values) {
		super();
		memory = new String[MEM_SIZE];
		for (int i = 0; i < MEM_SIZE; i++) {
			setByte(i, values[i]);
		}
	}

	/**
	 * Returns a single byte from memory.
	 * 
	 * @param address location of the byte.
	 * @return the byte.
	 */
	public String getByte(final int address) {
		return memory[address];
	}

	/**
	 * Stores a single byte into memory.
	 * 
	 * @param address the location for the byte.
	 * @param value the value for the byte.
	 */
	public void setByte(final int address, final String value) {
		String temp = value;
		
		for (int i = 0; i < BYTE_LENGTH - value.length(); i++) {
			temp = "0" + temp;
		}
		
		memory[address] = temp;
	}

	/**
	 * Returns a word (two bytes) from memory.
	 * 
	 * @param address location of the high order byte.
	 * @return the word.
	 */
	public String getWord(final int address) {
		String value = memory[address] + memory[address + 1];
		return value;
	}

	/**
	 * Stores a word (two bytes) into memory.
	 * 
	 * @param address the location of the high order byte.
	 * @param value the value to store.
	 */
	public void setWord(final int address, final String value) {
		String temp = value;
		for (int i = 0; i < WORD_LENGTH - value.length(); i++) {
			temp = "0" + temp;
		}
		String hob = temp.substring(0, BYTE_LENGTH);
		String lob = temp.substring(BYTE_LENGTH);
		memory[address] = hob;
		memory[address + 1] = lob;
	}
}
